package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"iot-base/common/cache"
	"iot-base/common/ctrltype"
	"iot-base/common/notify"

	"net"
	"time"
)

func runSetting(expression []byte, uid string) {
	if uid != "" {
		newV := bytes.ReplaceAll(expression, []byte("$UID$"), []byte(uid))
		conns, err := net.DialTimeout("tcp", "127.0.0.1:37125", 3*time.Second)
		if conns != nil {
			defer conns.Close()
		}
		if err != nil {
			fmt.Println("conn server err:")
			return
		}
		WriteDt(newV, conns)
		fmt.Println("send:", string(expression), string(newV), uid)
		var resConf ResConf
		readbuff := ReadDt(conns)
		err = json.Unmarshal(readbuff, &resConf)
		if err != nil {
			fmt.Println("readbuf:", string(readbuff), uid, resConf, err)
		}

	}
}

func init() {
	notify.SubOnline(func(pMsg *notify.OnlineNotify) {
		pThing, _ := cache.GetThing(pMsg.TID)
		if pThing == nil {
			return
		}

		if pThing.Thing.ModelID == "m_smartBoxForPolice" {
			uid, ok := pThing.Params["UID"]

			fmt.Println("------------on box online-----------", uid, ok)
			if ok {
				cmds := []string{"setconf.trap"}
				for _, id := range cmds {
					expression := cache.GetModelExpressionByTrigger("m_smartBoxForPolice", "online", id)
					//fmt.Println("------------on box online-----------", expression)
					runSetting(expression, uid)
				}
				fmt.Println("***************")

			}
			//RunSetIPCs(pMsg.TID)
			pThing, _ := cache.GetThing(pMsg.TID)
			if pThing != nil {
				mac := pThing.GetThingParam("mac", "")
				//macOld =
				if mac == "" {
					pCmd := &ctrltype.CtrlCmd{
						ID:      "GetConf",
						ThingID: pMsg.TID,
					}
					notify.Ctrl(pCmd, 2*time.Second, func(pResult *ctrltype.CtrlResult) {
						if pResult != nil && pResult.Result != nil {
							v, _ := pResult.Result["mac"]
							if v != nil && v != "" {
								pThing.SetThingParam("mac", v.(string))
							}
							getData(uid, pMsg.TID, pThing)

						}
					}, true)
				}
			}
		}
	})
}
